<?

include "../lib/db.php";
include "../lib/tbatv_lib.php";
include "../lib/admin_controller.php";
include "../lib/notification_controller.php";

$tbatvController = new tbatvController();
$adminController = new adminController();
$notificationController = new notificationController();

$eventyear = date('Y');
if ($_REQUEST['week'] > 0) {
	$current_week = sanatizeGet($_REQUEST['week']);
} else {
	$current_week = $tbatvController->getCurrentWeek();
}

// Don't SMS people old results
if ($current_week == $tbatvController->getCurrentWeek()) {
    $send_updates = True;
} else {
    $send_updates = False;
}

$all_events_query_filter = "SELECT eventid, name FROM events WHERE year = '$eventyear'AND week = '$current_week' AND official = '1'";
echo "<p>You can use ?week=weekcode, otherwise autodetected.</p>";
echo "Grabbing all events from year $eventyear and week $current_week <br />";
$all_events_query = mysql_query($all_events_query_filter);

echo "About to process " . mysql_num_rows($all_events_query) . " events<br />";

while($s=mysql_fetch_array($all_events_query)) {
	$eventid = $s["eventid"];
	$eventname = $s["name"];
	$event = new Event($eventid);
	print "<br />event built $eventname ($eventid)<br />";

	$list_of_new_matches = $adminController->getListOfNewMatches($event);

	print "got match list<br />";

	foreach($list_of_new_matches as $new_match) {
		$search_filter = "SELECT matchid FROM matches WHERE event = '{$new_match->getEventID()}' AND complevel = '{$new_match->getComplevel()}' AND matchnumber = '{$new_match->getMatchNumber()}'";
		$search_query = mysql_query($search_filter);
		if (mysql_num_rows($search_query) > 0) {
			$match_info = mysql_fetch_array($search_query);
			$matchid = $match_info["matchid"];
			$old_match = new Match($matchid);
			
			if (($old_match->getRedScore() != $new_match->getRedScore()) OR
				($old_match->getBlueScore() != $new_match->getBlueScore()) OR
				($old_match->getTeams('red') != $new_match->getTeams('red')) OR
				($old_match->getTeams('blue') != $new_match->getTeams('blue'))) {
				
				$new_match->update($matchid);
				if ($adminController->checkMatchCompletion($new_match)) {
					echo "Match {$new_match->getMatchNumber()} completed.<br />";
					$notificationController->smsByTeams($new_match);
					$notificationController->tweet($new_match);
				}
			} else {
				//echo "matches identical <br />";
			}
		} else {
		    if ($new_match->isSane()) {
    			$new_match->insert();
    			if ($adminController->checkMatchCompletion($new_match)) {
    				echo "MATCH COMPLETION<br />";
    				if ($send_updates) {
    				    echo "SENDING UPDATES<br />";
        				$notificationController->smsByTeams($new_match);
        				$notificationController->tweet($new_match);
        			}
    			}
    		}
		}
	}
}
	
print "done<br />";

?>